import React,{useState,useEffect} from 'react';
import { Button, Card ,Divider, Radio, Table,Space,Modal,Form,Input,Upload,message,Popconfirm} from 'antd';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import type { UploadChangeParam } from 'antd/es/upload';
import { EditOutlined ,DeleteOutlined,PlusOutlined,LoadingOutlined} from '@ant-design/icons';

import type { ColumnsType } from 'antd/es/table';
import {getTrademark,saveTradmark,removeTrademark} from "@/api/product/index"
import styles from  "./index.module.less";
// antd
interface DataType {
  id:number;
  tmName: string;
  logoUrl: string;
}


function Trademark() {

  const [form] = Form.useForm();
  // trademark数据设置
  const [trademark,setTrademark] = useState([]);
  // 分页数据的设置
  const [page,setPage] = useState({
    total:3,
    pageSize:3,
    current:1,
  })
  // 表格loading
  const [loading,setLoading] = useState(false)
  // 设置模态框
  const [open,setOpen] = useState(false)
  //table切换页面时触发的函数
  const changePage = (current:number,pageSize:number) =>{
    setLoading(true)
    getTrademark(current,pageSize).then((value:any)=>{
      // console.log(value.data);  
      setTrademark((trademark)=>{
        return trademark =value.data.records
      })
      setPage((page)=>{
        return page= {
          total:value.data.total,
          pageSize:value.data.size,
          current:value.data.current
        }
      })
      setLoading(false)
    })
  }
  // 定义模态框的标题
  const [modalTitle,setMoadlTitle] = useState("")
   // 图片
   const [imageUrl, setImageUrl] = useState<string>();
     // 获取id
  const [rowId,setId] = useState(null) 
  // table表格数据
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      align: "center",
      // dataIndex: 'name',
     render(rows, record, index) {
        // console.log(rows,record);
        return (page.current - 1) * 3 + index + 1;
    },
    },
    {
      title: '品牌名称',
      align: "center",
      dataIndex: 'tmName',
    },
    {
      title: '品牌LOGO',
      align: "center",
      dataIndex: 'logoUrl',
      render(rows) {
        return (
            <img
                width={80}
                height={70}
                src={rows}
                alt=""
            />
        );
    },
    },
    {
      title: '操作',
      align: "center",
      // width:200,
      // dataIndex: 'operation',
      render(rows,record) {
        return (
            <Space>
              
                <Button
                    icon={<EditOutlined />}
                    size={'small'}
                    type="primary"
                    style={{backgroundColor:'#fed71a',borderColor:'#fed71a'}}
                    onClick={()=>{
                      setOpen(true)
                      setMoadlTitle("修改品牌")
                      // console.log(rows.tmName);
                      // setInfo(rows)  
                      setId(rows.id)                     
                      form.setFieldsValue(rows ); 
                      setImageUrl(rows.logoUrl)
                    }}
                >
                   修改
                </Button>

                <Popconfirm title="Are you sure？" okText="Yes" cancelText="No"
                onConfirm={async()=>{
                  await removeTrademark(record.id)
                  changePage(page.current,3)
                }}
                >
                <Button
                    size={'small'}
                    type="primary"
                    danger
                    icon={<DeleteOutlined />}      
                >
                    删除
                </Button>
                </Popconfirm>
            </Space>
            )}
    },
  ];

  // 表单完成
  const onFinish = (values: any) => {
    console.log('Success:', values);
    form.resetFields();
  };
  // 表单失败
  const onFinishFailed = (errorInfo: any) => {
    console.log('Failed:', errorInfo);
  };
  // upload上传之前
  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('你只能上传jpg或者png图片');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片必须小于2mb');
    }
    return isJpgOrPng && isLt2M;
  };
   // 获取64位
  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  // 控制上传
  const [flag, setFlag] = useState(false);
  const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
    // console.log(1,info);
    // console.log(1);
    if (info.file.status === 'uploading') {
      setFlag(true);
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj as RcFile, url => {
        setFlag(false);
        setImageUrl(url);
      });
    }
  };
 
  const uploadButton = (
    <div>
      {flag ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );
  const [logoUrl,setLogoUrl] = useState("")
  const normFile = (e: any) => {
    // console.log('Upload event:', e);
    // console.log(e.file.response.data);
    if ((e.file.response||{}).data  ) {
      // console.log(e.file.response.data);
      setLogoUrl(e.file.response.data)
    }
    // setLogoUrl(e.)
    if (Array.isArray(e)) {
        return e;
    }
    return e && e.fileList;
};
const [ivalue,setIvalue]  =useState("")

const handlerOpne = async ()=>{
  // console.log(rowId);
  
  if (rowId) {
    await saveTradmark({
      id:rowId,
      logoUrl:logoUrl,
      tmName:ivalue
    })
    changePage(page.current,3)
  }else{
    await saveTradmark({
      logoUrl:logoUrl,
      tmName:ivalue
    })
    changePage(Math.ceil(page.total/3),3)
    // getTrademark(Math.ceil(page.total/3),3).then((value:any)=>{
    //   // console.log(value.data);  
    //   setTrademark((trademark)=>{
    //     return trademark =value.data.records
    //   })
    //   setPage((page)=>{
    //     return page= {
    //       total:value.data.total,
    //       pageSize:value.data.size,
    //       current:value.data.current
    //     }
    //   })
      // setLoading(false)
    // })
  }
  setId(null) 
  setOpen(false)
  form.resetFields()
  setImageUrl("") 

}


// 模拟挂载
useEffect(()=>{
  changePage(page.current,3)
},[])
  return(
  <>
  {/* <Card   style={{ width: 1300 }} hoverable > */}
  <div>
      <Button type="primary" icon={<PlusOutlined />} onClick={() => {setOpen(true);setMoadlTitle("添加品牌")} } > 添加</Button>
      <Modal
        title={modalTitle}
        visible={open}
        onOk={handlerOpne}
        onCancel={() => {setOpen(false);form.resetFields()} }
        centered
        destroyOnClose={true}
      >
      <Form
      form={form}
      // preserve={false}
      name="basic"
      // labelCol={{ span: 8 }}
      // wrapperCol={{ span: 16 }}
      // initialValues={{ remember: true }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
      autoComplete="off"
    >
      <Form.Item
        label="品牌名称"
        name="tmName"
        rules={[{ required: true, message: '品牌名称必须输入!' }]}  
      >
        <Input  value={ivalue} onChange={(e)=>setIvalue(e.target.value)}/>
      </Form.Item>

      <Form.Item
        label="品牌Logo"
        name="logo"
        rules={[{ required: true, message: '上传的图片必须是jpg，且不能大于2mb' }]}
        valuePropName="fileList"
        getValueFromEvent={normFile}
      >
     
      <Upload
      // name="avatar"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload"
      beforeUpload={beforeUpload}
      onChange={handleChange}
      withCredentials={true}
    >
      {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: 100,height:100 }} /> : uploadButton}
    </Upload>
   
      </Form.Item>
      <Form.Item>
       <div style={{fontSize:1,color:'rgb(0 0 0 / 45%)',marginTop:-30,marginLeft:"15%"}}>上传的图片必须是jpg且不能大于2M</div>
    </Form.Item>
    </Form>
      </Modal>
      <Divider />
      <Table
      className={styles.cl}
        rowKey={"id"}
        bordered
        columns={columns}
        dataSource={trademark}
        loading={loading}
        pagination={{
          // pageSize: 3,
          ...page,
          showQuickJumper:true,
          pageSizeOptions:[3, 5, 7, 10],
          // total : 85,
          // current:1,
          showTotal:(total) => `共 ${total} 条`,
          style:{
            display:'flex',
            justifyContent:'flex-start'
          },
          onChange:changePage
        }
        }
      />
    </div>
  {/* </Card> */}
</>
  )
 }
export default Trademark;